package com.huiyun.project.pay.biz.kit;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.huiyun.project.common.core.util.SpringUtils;
import com.huiyun.project.pay.biz.entity.PayChannel;
import com.huiyun.project.pay.biz.service.PayChannelService;

import java.io.Serializable;

/**
 * 支付配置工具类
 *
 * @author tiger
 */
public class PayConfigKit implements Serializable {

    public static void init(String appId, String... args) {
        PayChannel payChannel = SpringUtils.getBean(PayChannelService.class).getByChannelAppId(appId);
        Assert.notNull(payChannel, "无效的渠道配置信息");
        JSONObject jsonObject = JSONObject.parseObject(payChannel.getParam());
        String channelId = payChannel.getChannelId();
        Assert.notBlank(channelId, "无效的渠道编号");
        if (channelId.indexOf("WX_") != -1) {
            WxPayApiConfig apiConfig = null;
            try {
                apiConfig = WxPayApiConfigKit.getApiConfig(appId);
            } catch (Exception ex) {
                apiConfig = WxPayApiConfig.builder()
                        .appId(payChannel.getChannelAppId())
                        .mchId(payChannel.getChannelMchId())
                        .partnerKey(jsonObject.getString("partnerKey"))
                        .certPath(StrUtil.format(jsonObject.getString("certPath"), payChannel.getMchId(), channelId))
                        .domain(jsonObject.getString("domain"))
                        .build();
            }
            WxPayApiConfigKit.setThreadLocalWxPayApiConfig(apiConfig);
        } else if (channelId.indexOf("ALIPAY_") != -1) {
            AliPayApiConfig aliPayApiConfig = null;
            try {
                aliPayApiConfig = AliPayApiConfigKit.getApiConfig(appId);
            } catch (Exception e) {
                aliPayApiConfig = AliPayApiConfig.builder()
                        .setAppId(payChannel.getChannelAppId())
                        //.setAliPayPublicKey(jsonObject.getString("publicKey"))
                        .setAliPayPublicKey(jsonObject.getString("aliPayPublicKey"))
                        .setCharset("UTF-8")
                        .setPrivateKey(jsonObject.getString("privateKey"))
                        .setServiceUrl(jsonObject.getString("serverUrl"))
                        .setSignType("RSA2")
                        .build();
            }
            AliPayApiConfigKit.setThreadLocalAliPayApiConfig(aliPayApiConfig);

        }

    }
}
